package com.changgou.weixin.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.weixin.service.PayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

/**
 * @author ：zhangchen
 * @date ：Created in 2020/1/15
 * @description ：
 * @version: 1.0
 */
@RestController
@RequestMapping("/weixin/pay")
public class PayController {
    @Autowired
    private PayService payService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /***
     * 创建支付二维码
     * @return
     */
    @GetMapping("/create/native")
    public Result createNavite(@RequestParam Map<String,String> paramsMap){
        Map<String, String> resultMap = payService.createNativePay(paramsMap);
        return new Result(true, StatusCode.OK,"创建二维码预付订单成功",resultMap);
    }

    /**
     * 支付状态查询
     * @return
     */
    @GetMapping("/status/query")
    public Result queryStatus(@RequestParam String orderId){
        Map<String, String> resultMap = payService.queryPayStatus(orderId);
        return new Result(true, StatusCode.OK,"查询支付状态成功",resultMap);
    }

    /**
     * 支付结果回调通知
     * @return
     */
    @RequestMapping("/notify/url")
    public String notifyurl(HttpServletRequest request) throws Exception {
        ServletInputStream is = request.getInputStream();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len=0;
        while((len=is.read(buffer))!=-1){
            bos.write(buffer,0,len);
        }

        byte[] bytes = bos.toByteArray();

        String xmlresult = new String(bytes, "UTF-8");
        System.out.println(">>>xmlresult>>>"+xmlresult);

        Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlresult);
        System.out.println(">>>resultMap>>>"+resultMap);

        rabbitTemplate.convertAndSend("exchange.order", "queue.order", JSON.toJSONString(resultMap));

        String result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        return result;
    }

}

